package stu.day9_day18;

import java.util.Comparator;
import java.util.TreeSet;

public class Solution {
    public ListNode mergeKLists(ListNode[] lists) {

        TreeSet<ListNode> queue = new TreeSet<>(new Comparator<ListNode>() {
            @Override
            public int compare(ListNode o1, ListNode o2) {
                return o1.val-o2.val;
            }
        });

        for(int i=0;i<lists.length;i++){
            if(lists[i]!=null) {
                queue.add(lists[i]);
            }
        }

        if(queue.isEmpty()){
            return null;
        }

        ListNode head = new ListNode(-1);
        ListNode tail = head;


        while (!queue.isEmpty()){
            ListNode node = queue.pollFirst();
            if(node.next!=null){
                queue.add(node.next);
            }
            tail.next = node;
            tail = tail.next;

        }
        return head.next;

    }
}
